package com.xywy.me;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.umeng.analytics.MobclickAgent;
import com.xywy.R;
import com.xywy.common.BaseFragment;
import com.xywy.common.FragmentMainActivity;
import com.xywy.common.constants.ConstantValue;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.greendao.BaseDao;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.MLog;
import com.xywy.common.widget.MyProgress;
import com.xywy.find.RemindListActivity;
//import com.xywy.jtys.TwAddActivity;
import com.xywy.me.bean.Jtcy;
import com.xywy.me.bean.UserKeeper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 名称: 我 描述:
 * 
 * 类型: JAVA 最近修改时间:${date} ${time}
 * 
 * @since 2014/8/2
 * @author xgd
 */
public class MeFragment extends BaseFragment {

	private static final String TAG = "MeFragment";
	private FragmentMainActivity mactivity;
	private RelativeLayout infor;
	private RelativeLayout wdys;
	private RelativeLayout mydevice;
	private RelativeLayout wdsc;
	private RelativeLayout wdtx;
	/** 家庭成员 */
	// private RelativeLayout jtcy;
	private RelativeLayout set;

	private ImageView userIcon;
	private TextView account;
	private TextView nick;
	/** 家庭成员列表 */
	private List<Jtcy> jtcys; // 返回的所有用户数据

	private String userid = "";
	private String mobile = "";
	private String userIconStr = "";

	// private JtcyDao dao;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mactivity = (FragmentMainActivity) activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	// 根布局
	private View rootView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		rootView = inflater.inflate(R.layout.fragment_me, null);
		myProgress = new MyProgress(mactivity, 10);
		this.preInit();
		// 初始化View
		this.initView();

		this.setListener();
		this.loadData();
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	private void preInit() {
		SharedPreferences sp = mactivity.getSharedPreferences("config",
				Context.MODE_PRIVATE);
		userid = UserKeeper.getCurrentUser(getActivity()).getUserid();
		mobile = sp.getString("mobile", "");

		BaseDao baseDao = BaseDao.getInstance(mactivity);
		// dao = baseDao.getJtcyDao();
	}

	/**
	 * 初始化View
	 */
	private void initView() {
		infor = (RelativeLayout) rootView.findViewById(R.id.rl_me_infor);
		// wdys= (RelativeLayout) rootView.findViewById(R.id.rl_me_wdys);
		mydevice = (RelativeLayout) rootView.findViewById(R.id.rl_me_mydevice);
		wdsc = (RelativeLayout) rootView.findViewById(R.id.rl_me_wdsc);
		wdtx = (RelativeLayout) rootView.findViewById(R.id.rl_me_wdtx);
		// jtcy = (RelativeLayout) rootView.findViewById(R.id.rl_me_jtcy);
		set = (RelativeLayout) rootView.findViewById(R.id.rl_me_set);

		infor.setBackgroundColor(mactivity.getResources().getColor(
				R.color.white));
		wdys.setBackgroundColor(mactivity.getResources()
				.getColor(R.color.white));
		mydevice.setBackgroundColor(mactivity.getResources().getColor(
				R.color.white));
		wdsc.setBackgroundColor(mactivity.getResources()
				.getColor(R.color.white));
		wdtx.setBackgroundColor(mactivity.getResources()
				.getColor(R.color.white));
		set.setBackgroundColor(mactivity.getResources().getColor(R.color.white));

		userIcon = (ImageView) rootView.findViewById(R.id.me_cover_user_photo);
		account = (TextView) rootView.findViewById(R.id.tv_me_account);
		nick = (TextView) rootView.findViewById(R.id.tv_account_nick);

	}

	/**
	 * 事件监听
	 */
	private void setListener() {
		infor.setOnClickListener(onClickListener);
		// wdys.setOnClickListener(onClickListener);
		wdsc.setOnClickListener(onClickListener);
		mydevice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent myDeviceIntent = new Intent(mactivity,
						RemindListActivity.class);
				startActivity(myDeviceIntent);

			}
		});
		wdtx.setOnClickListener(onClickListener);
		// jtcy.setOnClickListener(onClickListener);
		set.setOnClickListener(onClickListener);
	}

	View.OnClickListener onClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View view) {

			Class cl = null;
			String str = "remindDelete";
			int infor = 0;
			switch (view.getId()) {
			case R.id.rl_me_infor:
				cl = InforActivity.class;
				infor = 1;
				break;
			case R.id.rl_me_mydevice:
				break;
			case R.id.rl_me_wdsc:
				cl = CollectActivity.class;
				break;
			case R.id.rl_me_wdtx:
				MobclickAgent.onEvent(mactivity, "L001");
				cl = RemindListActivity.class;
				break;
			case R.id.rl_me_set:
				cl = SetupActivity.class;
				break;
			}
			Intent intent = new Intent(mactivity, cl);
			intent.putExtra("remindDelete", str);
			if (infor == 1) {
				intent.putExtra("jtcy", mainAccout); // 主用户信息
			}
			if (infor == 5) {
				intent.putExtra("jtcys", (Serializable) jtcys);
			}
			startActivity(intent);
		}
	};

	/**
	 * Fragmengt唯一标识
	 * 
	 * @return
	 */
	@Override
	public int getID() {
		return ConstantValue.FG_ME;
	}

	private void loadData() {
		sendMsg();

	}

	MyProgress myProgress;
	JSONObject msgBack = null;
	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			myProgress.stop();
			try {
				msgBack = new JSONObject(msg.obj.toString());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			if (msgBack.optInt("state") == ResultCode.SUCCESS) {
				// 解析返回的数据
				jtcys = jsonAny(msg.obj.toString());

				userIconStr = msgBack.optString("avatar");
				if (!userIconStr.endsWith(".jpg")) { // 判断是否以.jpg结尾
					userIconStr += ".jpg";
				}
				mainAccout.setIcon(userIconStr);
				circleImageView(userIconStr, userIcon);
				account.setText(mobile);
				nick.setText(mainNick);
			} else {
				Toast.makeText(mactivity, msgBack.optString("error"),
						Toast.LENGTH_LONG).show();
			}
		}
	};

	private void circleImageView(String url, ImageView imageView) {
		// 圆形头像
		imageLoader.displayImage(url, imageView, options,
				new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						if (loadedImage != null) {
							((ImageView) view)
									.setScaleType(ImageView.ScaleType.CENTER_CROP);
							boolean firstDisplay = !displayedImages
									.contains(imageUri);
							if (firstDisplay) {
								FadeInBitmapDisplayer.animate((ImageView) view,
										500);
								displayedImages.add(imageUri);
							}
						}
					}

					@Override
					public void onLoadingCancelled(String s, View view) {

					}

					@Override
					public void onLoadingStarted(String s, View view) {

					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						Throwable cause = failReason.getCause();
						MLog.e(TAG, cause.toString());
					}
				});
	}

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;

	// 处理网络请求
	public void sendMsg() {

		myProgress.start();
		paramsParser = new Parser();

		// 封装参数
		params = new HashMap<String, Object>();

		// 请求路径
		paramsParser.action = getString(R.string.get_account_data_list);
		// 请求方式
		paramsParser.request = "get";
		// 请求参数
		params.put("userid", userid);

		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = mactivity;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			handler.sendMessage(message);
		}
	};

	private String mainNick = ""; // 主用户的昵称
	/**
	 * 1 获取所有的用户信息， 2.将 accountid ： 子用户id（0为 主用户的信息单独存储用于显示
	 * 
	 * @param jsonStr
	 * @return
	 */
	private Jtcy mainAccout = new Jtcy();

	private List<Jtcy> jsonAny(String jsonStr) {

		List<Jtcy> list = Collections.synchronizedList(new ArrayList<Jtcy>());
		// 分别实例化，进行潜拷贝
		Jtcy jtcy = new Jtcy();
		try {
			JSONObject jsonObject = new JSONObject(jsonStr);
			JSONArray jsonArray = jsonObject.getJSONArray("accounts");
			if (null != jsonArray && jsonArray.length() > 0) {
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject json = jsonArray.getJSONObject(i);
					Jtcy cy = jtcy.clone();

					cy.setAccountid(json.optLong("accountid"));

					if (json.optInt("accountid") == 0) {
						mainNick = json.optString("accountstr");
					}
					cy.setAccountstr(json.optString("accountstr"));
					cy.setSex(json.optString("sex"));
					cy.setHeight(json.optString("height"));
					cy.setBirthday(json.optString("birthday"));

					if (json.optInt("accountid") == 0) {
						// mainAccout = cy;
					}
					// 存储到本地db
					list.add(cy);
					/*
					 * dao.deleteAll(); long ret= dao.insert(cy);
					 * MLog.i(TAG,"存储到本地db :"+ret);
					 */
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return list;
	}

	// ====ImageLoader start====
	public static final List<String> displayedImages = Collections
			.synchronizedList(new LinkedList<String>());
	// ImageLoaderOptions
	private DisplayImageOptions options;

	// ImageLoader
	protected ImageLoader imageLoader = ImageLoader.getInstance();

	private void initImageLoader() {
		options = new DisplayImageOptions.Builder()
				// .showImageForEmptyUri(R.drawable.ic_error) // resource or
				// drawable
				.showImageOnFail(R.drawable.imageloader_error)
				// resource or drawable
				.showStubImage(R.drawable.imageloader_default)
				.resetViewBeforeLoading(false)
				// default
				.cacheInMemory(true)
				.cacheOnDisc(true)
				// 精准
				.imageScaleType(ImageScaleType.EXACTLY)
				// ARGB_8888 每个像素要4字节~带透明度的颜色, 默认色样
				// RGB_565 每个像素要2字节~不带透明度的颜色
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new RoundedBitmapDisplayer(10)).build();
	}
	// ====ImageLoader end====
}
